local ImageButton = require "widgets/imagebutton"
local Image = require "widgets/image"
local Widget = require "widgets/widget"
local t_util = require "libs/tableutil"
local c_mana = require "libs/ctrlmanager"
local e_util = require "libs/entutil"


local ECTRL = Class(Widget, function(self, inv, owner)
    Widget._ctor(self, "ECTRL")
    if c_mana:GetUIHide() then self:Hide() end

    local equipslots = inv.equip
    self.eslots = {}
    local slot_data = {}
    t_util:Pairs(equipslots, function(slot, itemslot) 
        table.insert(self.eslots, { slot = slot, itemslot = itemslot } )
        table.insert(slot_data, slot)
    end)
    c_mana:SetSlotData(slot_data)
    table.sort(self.eslots, function(a, b) return a.itemslot:GetPosition().x < b.itemslot:GetPosition().x end)
    if #self.eslots < 2 then return end

    local a_pos = self.eslots[1].itemslot:GetPosition()
    self.img_size = self.eslots[1].itemslot.bgimage:GetScaledSize()
    self.img_space = self.eslots[2].itemslot:GetPosition().x - a_pos.x - self.img_size
    local img_a_space = self.img_size+self.img_space
    
    -- root
    local savepos = c_mana:GetUIInitPos()

    self.init_x = a_pos.x
    self.init_y = 4*self.img_size

    local init_x = savepos.x or self.init_x
    local init_y = savepos.y or self.init_y
    self:SetPosition(init_x, init_y)
    local root = self:AddChild(Widget("ec_root"))

    -- frame
    local bg_width = (#self.eslots+1)*img_a_space
    local bg_height = 3*img_a_space
    local f_atlas = resolvefilepath(CRAFTING_ATLAS)
    self.frame = root:AddChild(Widget("frame"))
    self.frame:SetPosition(bg_width/2-img_a_space/2, bg_height/2-img_a_space/2)
    self.frame:SetHoverText(STRINGS.LMB.."可拖拽", {offset_y = 2*self.img_size, colour = UICOLOURS.GOLD, fontsize = 30})
    ---------- fill
    local fill = self.frame:AddChild(Image(f_atlas, "backing.tex"))
    fill:ScaleToSize(bg_width + 10, bg_height + 18)
    fill:SetTint(1,1,1,0.65)
    ---------- line
    local left = self.frame:AddChild(Image(f_atlas, "side.tex"))
    local right = self.frame:AddChild(Image(f_atlas, "side.tex"))
    local top = self.frame:AddChild(Image(f_atlas, "top.tex"))
    local bottom = self.frame:AddChild(Image(f_atlas, "bottom.tex"))
    left:SetPosition(-bg_width / 2 - 10, 1)
    right:SetPosition(bg_width / 2 + 10, 1)
    top:SetPosition(0, bg_height / 2 + 10)
    bottom:SetPosition(0, -bg_height / 2 - 8)
    left:ScaleToSize(-26, -(bg_height - 20))
    right:ScaleToSize(26, bg_height - 20)
    top:ScaleToSize(bg_width+33, 38)
    bottom:ScaleToSize(bg_width+33, 38)

    -- button
    self.line_fight = root:AddChild(Widget("line_fight"))
    self.line_walk = root:AddChild(Widget("line_walk"))
    self.about_light = root:AddChild(Widget("about_light"))
    self.about_eat = root:AddChild(Widget("about_eat"))
    self.line_walk:SetPosition(0, img_a_space)
    self.about_light:SetPosition(0, img_a_space*2)
    self.about_eat:SetPosition(img_a_space*2, img_a_space*2)

    local r_text_slot = "这个格子已启用\n"..STRINGS.LMB.."忽略此栏    "..STRINGS.RMB.."选择装备\n".."或拖动装备至此"
    local w_text_slot = "这个格子已禁用\n"..STRINGS.LMB.."启用此栏    "..STRINGS.RMB.."选择装备\n".."或拖动装备至此"

    local i = 0
    t_util:Pairs(self.eslots, function(_, eslot)
        local img = eslot.itemslot.bgimage
        local xml, tex = img.atlas, img.texture
        local pos_x = i*img_a_space
        self.line_fight[eslot.slot] = self:MakeButton_Slot(self.line_fight, "fight", eslot.slot, xml, tex, pos_x, r_text_slot, w_text_slot)
        self.line_walk[eslot.slot] = self:MakeButton_Slot(self.line_walk, "walk", eslot.slot, xml, tex, pos_x, r_text_slot, w_text_slot)
        i = i+1
    end)

    local r_pos = i*img_a_space
    self.line_fight.turn = self:MakeButton_Turn(self.line_fight, "fight", GetScrapbookIconAtlas("icon_damage.tex"), "icon_damage.tex", r_pos, "战斗切装备：启用", "战斗切装备：禁用")
    self.line_walk.turn = self:MakeButton_Turn(self.line_walk, "walk", GetScrapbookIconAtlas("icon_clothing.tex"), "icon_clothing.tex", r_pos, "移动切装备：启用", "移动切装备：禁用")
    
    self.about_light.slot = self:MakeButton_Slot(self.about_light, "light", "slot", "images/hud.xml", "sisturn_slot_petals.tex", 0, STRINGS.LMB.."装备光源\n"..STRINGS.RMB.."选择光源\n".."或拖拽光源至此")
    self.about_light.turn = self:MakeButton_Turn(self.about_light, "light", GetScrapbookIconAtlas("icon_lightbattery.tex"), "icon_lightbattery.tex", img_a_space, "自动切光源：启用", "自动切光源：禁用")

    self.about_eat.slot = self:MakeButton_Slot(self.about_eat, "eat", "slot", "images/hud.xml", "inv_slot_morsel.tex", 0, STRINGS.LMB.."吃掉它!\n"..STRINGS.RMB.."选择食物\n".."或拖拽食物至此")
    self.about_eat.turn = self:MakeButton_Turn(self.about_eat, "eat", GetScrapbookIconAtlas("icon_hunger.tex"), "icon_hunger.tex", img_a_space, "自动吃饭：启用", "自动吃饭：禁用")
end)


function ECTRL:MakeButton_Turn(parent, id, xml, tex, posx, r_text, w_text)
    local btn = parent:AddChild(ImageButton(xml, tex))
    local btn_size = btn:GetSize()
    local btn_scale = self.img_size/btn_size
    btn:SetNormalScale(btn_scale)
    btn:SetFocusScale(btn_scale*1.4)
    btn:ForceImageSize(self.img_size, self.img_size)
    btn:SetPosition(posx, 0)
    btn.value = c_mana:GetBtnTurnValue(id)

    local function install(val)
        btn:SetHoverText(val and r_text or w_text, {offset_y = self.img_size})
        local img = btn.image
        if val then img:SetTint(1,1,1,1) 
        else img:SetTint(1,0,0,1) end
        c_mana:SetBtnTurnValue(id, val)
    end

    install(btn.value)
    btn.OnMouseButton = function(btn, press, down, ...)
        if down then return end
        if press == MOUSEBUTTON_LEFT then
            btn.value = not btn.value
            install(btn.value)
        end
    end
    return btn
end


function ECTRL:MakeButton_Slot(parent, category, slot, xml, tex, posx, r_text, w_text)
    local btn = parent:AddChild(ImageButton(xml, tex))
    local btn_size = btn:GetSize()
    local btn_scale = self.img_size/btn_size
    btn:SetNormalScale(btn_scale)
    btn:SetFocusScale(btn_scale*1.2)
    btn:ForceImageSize(self.img_size, self.img_size)
    btn:SetPosition(posx, 0)
    local data = c_mana:GetBtnSlotData(category, slot)
    btn.value = data.value == nil and true or data.value        -- 默认为true
    btn.img_show = btn:AddChild(Image())
    if c_mana:GetImgBan(category, slot) then
        btn.img_ban = btn:AddChild(Image("images/shroomcake_moreicons.xml", "wrong.tex"))
        btn.img_ban:ScaleToSize(self.img_size, self.img_size)
    end

    local function update_style(meta)
        btn:SetHoverText(btn.value and r_text or (w_text or r_text), {offset_y = 2*self.img_size})
        if btn.img_ban then
            if btn.value then 
                btn.img_ban:Hide()
            else
                btn.img_ban:Show()
            end
        end
        if meta.xml and meta.tex and TheSim:AtlasContains(meta.xml, meta.tex) then
            btn.img_show:SetTexture(meta.xml, meta.tex)
            btn.img_show:Show()
        else
            btn.img_show:Hide()
        end
    end
    update_style(data)

    -- item 未传入：设置默认data的贴图
    -- item 是实体：设置实体的贴图
    -- item 是空表：隐藏按钮贴图
    -- item 是null_huxi：表示这里置空
    btn.install = function(btn, item, fav)
        local data = c_mana:GetBtnSlotData(category, slot)
        local new_xml, new_tex, new_prefab = data.xml, data.tex, data.prefab
        if item then
            new_prefab = item.prefab
            if new_prefab == "null_huxi" then
                new_xml,new_tex = xml,tex
            else
                new_xml, new_tex = e_util:GetAtlasAndImage(item)
            end
        end
        update_style({
            xml = new_xml,
            tex = new_tex
        })
        local savedata = {
            value = btn.value,
            prefab = new_prefab,
            xml = new_xml,
            tex = new_tex,
            fav = data.fav,
        }
        if fav then
            savedata.fav = new_prefab
        end
        c_mana:SetBtnSlotData(category, slot, savedata)
    end
    
    btn.OnMouseButton = function(btn, press, down, ...)
        -- 按下
        if down then
            btn.pressit = true
        -- 点击
        elseif btn.pressit then
            btn.pressit = false
            if press == MOUSEBUTTON_LEFT then
                c_mana:LeftClick(btn, category, slot)
            elseif press == MOUSEBUTTON_RIGHT then
                c_mana:RightClick(btn, category, slot)
            end
        -- 拖动
        elseif press == MOUSEBUTTON_LEFT then
            c_mana:DragFn(btn, category, slot)
        end
    end
    return btn
end

function ECTRL:InitSelfPosition()
    self:StopFollowMouse()
    self:SetPosition(self.init_x, self.init_y)
    c_mana:SetUIInitPos({
        x = self.init_x,
        y = self.init_y,
    })
    self:ToHide(false)
end


function ECTRL:ToHide(hide)
    if hide then
        self:Hide()
    else
        self:Show()
    end
    c_mana:SetUIHide(hide)
end


local h_util = require "libs/hudutil"
h_util:ActivateUIDraggable(ECTRL, function(pos)
    c_mana:SetUIInitPos(pos)
end)

return ECTRL